import 'package:flutter/material.dart';
import 'package:flutter_wisave/widgets/AppColors.dart';
import 'package:flutter_wisave/widgets/deviceLinePie.dart';
import 'package:flutter_wisave/widgets/indicator.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:tdesign_flutter/src/theme/td_theme.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../../Tools/ToolsLocalStorage.dart';

// class DeviceData02 extends StatelessWidget {
//   const DeviceData02({super.key, required});

class DeviceData02 extends StatefulWidget {
  const DeviceData02({super.key});

  @override
  State<DeviceData02> createState() => _DeviceData02State();
}

class _DeviceData02State extends State<DeviceData02>
    with SingleTickerProviderStateMixin {
  late String currentDayDate = DateTime.now().toString().substring(0, 7);
  final NetworkService _networkService = NetworkService();
  List<dynamic> dataList = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _loadData();
  }

  //设备故障趋势
  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result['code'] == 200 && result['rows'] != null) {
        setState(() {
          dataList = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
        });
      } else {
        print('Error: ${result['msg']}');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>> _fetchData() async {
    final deptID = await LocalStorage.getstr('deptId');
    try {
      final response = await _networkService.get(
          '/plcTimer/malfunctionday/selectMalfunctionWeek?companyId=$deptID&date=$currentDayDate');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        throw Exception('deptList Failed to load data');
      }
    } catch (e) {
      print('deptList Error in _fetchData: $e');
      rethrow;
    }
  }

  String _formatDate(String dateString) {
    DateTime date = DateTime.parse(dateString);
    return '${date.month}.${date.day}';
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.all(16),
      child: Container(
        // width: double.infinity,
        // height: 100,
        padding: EdgeInsets.all(16.0),
        decoration: BoxDecoration(
          color: AppColors.cardColor,
          borderRadius: BorderRadius.circular(8.0),
          boxShadow: [
            BoxShadow(
              color: Colors.grey.withOpacity(0.2),
              blurRadius: 6.0,
            ),
          ],
        ),
        child: Column(children: [
          Row(
            children: [
              TDText(
                '设备故障趋势',
                font: TDTheme.of(context).fontBodyExtraLarge,
                textColor: AppColors.textPrimary,
              ),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              Indicator(
                color: Color(0xFF2AB6F7),
                text: '主机通讯',
                isSquare: true,
              ),
              SizedBox(width: 10),
              Indicator(
                color: Color(0xFF814FF3),
                text: '主机供电',
                isSquare: true,
              ),
              SizedBox(width: 10),
              Indicator(
                color: Color(0xFF53E0B1),
                text: '副机供电',
                isSquare: true,
              ),
            ],
          ),
          const SizedBox(height: 10),
          Row(
            children: [
              Indicator(
                color: Color(0xFFFCAA3F),
                text: '副机通讯',
                isSquare: true,
              ),
              SizedBox(width: 10),
              Indicator(
                color: Color(0xFFEF6B9C),
                text: '液压通讯',
                isSquare: true,
              ),
              SizedBox(width: 10),
              Indicator(
                color: Color(0xFFFD5864),
                text: '液压供电',
                isSquare: true,
              ),
            ],
          ),
          const SizedBox(height: 10),
          Container(
            height: 1,
            width: double.infinity,
            color: Colors.grey[200],
          ),
          const SizedBox(height: 10),
          ...dataList.map((data) {
            return SizedBox(
              child: Container(
                child: deviceLinePie(
                  date:
                      '${_formatDate(data['start'])}/${_formatDate(data['end'])}',
                  numberCount: 100,
                  // data['typeNameCounts'],
                  dataValue01: 20,
                  // data['typeNameCounts'],
                  dataValue02: 10,
                  // data['typeNameCounts'],
                  dataValue03: 40,
                  // data['typeNameCounts'],
                  dataValue04: 0,
                  // data['typeNameCounts'],
                  dataValue05: 0,
                  // data['typeNameCounts'],
                  dataValue06: 30,
                  // data['typeNameCounts'],
                ),
              ),
            );
          }).toList(),
        ]),
      ),
    );
  }
}
